/* 
 * File:   InsertTable.cpp
 * Author: vikrantsingh
 * 
 * Created on 2 November, 2013, 9:58 PM
 */

#include "InsertTable.h"
#include "Validation.h"
#include "../Sysfiles/SysCatalog.h"
#include "../PageLayout/Tuple.h"
#include"../Utils/Timer.h"

InsertTable::InsertTable() {
}

InsertTable::InsertTable(const InsertTable& orig) {
}

InsertTable::~InsertTable() {
}

STATUS_CODE InsertTable::run(QueryStructures *queryStruct) {
    Timer timer;
    timer.startTimer();
    //DEBUG("inside insertTable execute");
    int err = Validation::isValid();
    if (err != SUCCESS) {
        return err;
    }
    SysCatalog cat;
    Schema schema;
    err = cat.getSchema(queryStruct->tableName.c_str(), schema);
    if (err == TABLE_NOT_FOUND) {
        return err;
    }
    //insert into first values (10); queries like this col is not specified
    if (queryStruct->insertValues.size() != schema.numOfColumns) {
        return PARSE_FAILED;
    }
    
    Heap heapFile(queryStruct->tableName.c_str());
    for (int i = 0; i < queryStruct->insertValues.size(); i++) {
        DEBUG("insertValue[" << i << "]=" << queryStruct->insertValues[i]);
    }

    Tuple tuple(schema, queryStruct->insertValues);
    char *record = tuple.recordPreparation();
    for (int i = 0; i < tuple.getLength(); i++) {
        DEBUG("record after prep" << record[i]);
    }
    RIDStruct rid;
    err = heapFile.insertRecord(rid, tuple.getLength(), record);
    if (SUCCESS != err) {
        return err;
    }
    int numOfRecords = heapFile.getNoOfRecords();
    if (numOfRecords % 5000 == 0) {
        std::cout << "NUM OF RECORDS INSERTED=" << numOfRecords << endl;
    }
    if (USING_INDEX == true) {
        
        //MAKE ENTRY INTO INDEX

    }

    timer.updateNumberOfRows(numOfRecords);
    timer.endTimer();
    std::string elapsedTime = timer.getElapsedTimeInMilliSeconds();
    elapsedTime.append("  milliseconds");
    timer.updateExecutionTimeMessage(elapsedTime);
    return SUCCESS;
}